<template>
  <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 border border-white/20">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
      <!-- 筛选按钮组 -->
      <div class="flex flex-wrap items-center gap-3">
        <Button 
          :variant="selectedFilters.length === 0 ? 'primary' : 'outline'"
          size="md"
          @click="clearFilters"
        >
          全部
        </Button>
        
        <Button 
          :variant="showFavorite ? 'primary' : 'outline'"
          size="md"
          @click="toggleFavorite"
        >
          <svg class="w-4 h-4 mr-2" :class="showFavorite ? 'text-yellow-500' : 'text-gray-400'" viewBox="0 0 24 24">
            <path 
              stroke-linecap="butt" 
              stroke-linejoin="miter" 
              stroke-width="2" 
              :fill="showFavorite ? 'currentColor' : 'none'"
              :stroke="showFavorite ? 'none' : 'currentColor'"
              d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
            ></path>
          </svg>
          收藏
        </Button>
      </div>

      <!-- 搜索和筛选控件 -->
      <div class="flex flex-col sm:flex-row gap-3 w-full sm:w-auto">
        <!-- 搜索框 -->
        <div class="relative flex-grow">
          <Input
            v-model="searchQuery"
            placeholder="搜索题目..."
            :prefix-icon="SearchIcon"
            @input="handleSearch"
          />
        </div>

        <!-- 难度筛选（自定义下拉，支持悬浮高亮） -->
        <div class="relative w-full sm:w-auto">
          <Listbox v-model="selectedDifficulty" @update:modelValue="handleFilter">
            <div class="relative">
              <ListboxButton class="w-full px-4 py-3 pr-10 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm transition-all duration-200 text-left">
                {{ difficultyLabel }}
                <span class="absolute inset-y-0 right-3 flex items-center pointer-events-none">▼</span>
              </ListboxButton>
              <ListboxOptions class="absolute z-10 mt-1 w-full max-h-60 overflow-auto rounded-xl bg-white shadow-lg ring-1 ring-black/5 focus:outline-none">
                <ListboxOption v-for="opt in difficultyOptions" :key="opt.value" :value="opt.value" v-slot="{ active, selected }">
                  <li :class="[active ? 'bg-blue-500 text-white' : 'text-gray-900', 'cursor-pointer select-none py-2 px-4']">
                    {{ opt.label }}
                  </li>
                </ListboxOption>
              </ListboxOptions>
            </div>
          </Listbox>
        </div>

        <!-- 标签筛选（自定义下拉，支持悬浮高亮） -->
        <div class="relative w-full sm:w-auto">
          <Listbox v-model="selectedTag" @update:modelValue="handleFilter">
            <div class="relative">
              <ListboxButton class="w-full px-4 py-3 pr-10 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm transition-all duration-200 text-left">
                {{ tagLabel }}
                <span class="absolute inset-y-0 right-3 flex items-center pointer-events-none">▼</span>
              </ListboxButton>
              <ListboxOptions class="absolute z-10 mt-1 w-full max-h-60 overflow-auto rounded-xl bg-white shadow-lg ring-1 ring-black/5 focus:outline-none">
                <ListboxOption v-for="opt in tagOptions" :key="opt.value || 'all'" :value="opt.value" v-slot="{ active, selected }">
                  <li :class="[active ? 'bg-blue-500 text-white' : 'text-gray-900', 'cursor-pointer select-none py-2 px-4']">
                    {{ opt.label }}
                  </li>
                </ListboxOption>
              </ListboxOptions>
            </div>
          </Listbox>
        </div>

        <!-- 状态筛选（自定义下拉，支持悬浮高亮） -->
        <div class="relative w-full sm:w-auto">
          <Listbox v-model="selectedStatus" @update:modelValue="handleFilter">
            <div class="relative">
              <ListboxButton class="w-full px-4 py-3 pr-10 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm transition-all duration-200 text-left">
                {{ statusLabel }}
                <span class="absolute inset-y-0 right-3 flex items-center pointer-events-none">▼</span>
              </ListboxButton>
              <ListboxOptions class="absolute z-10 mt-1 w-full max-h-60 overflow-auto rounded-xl bg-white shadow-lg ring-1 ring-black/5 focus:outline-none">
                <ListboxOption v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value" v-slot="{ active, selected }">
                  <li :class="[active ? 'bg-blue-500 text-white' : 'text-gray-900', 'cursor-pointer select-none py-2 px-4']">
                    {{ opt.label }}
                  </li>
                </ListboxOption>
              </ListboxOptions>
            </div>
          </Listbox>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Input from '@/components/ui/Input.vue'
import Button from '@/components/ui/Button.vue'
import { Listbox, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/vue'

// 搜索图标
const SearchIcon = {
  template: `
    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
    </svg>
  `
}

interface Props {
  modelValue: {
    search: string
    difficulty: string
    tag: string
    status: string
    favorite: boolean
  }
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:modelValue': [value: typeof props.modelValue]
  search: []
  filter: []
}>()

// 响应式数据
const searchQuery = ref(props.modelValue.search)
const selectedDifficulty = ref(props.modelValue.difficulty)
const selectedTag = ref(props.modelValue.tag)
const selectedStatus = ref(props.modelValue.status)
const showFavorite = ref(props.modelValue.favorite)

// 可用标签
const availableTags = [
  { value: 'array', label: '数组' },
  { value: 'string', label: '字符串' },
  { value: 'linked-list', label: '链表' },
  { value: 'tree', label: '树' },
  { value: 'graph', label: '图' },
  { value: 'dynamic-programming', label: '动态规划' },
  { value: 'greedy', label: '贪心' },
  { value: 'backtracking', label: '回溯' },
  { value: 'binary-search', label: '二分查找' },
  { value: 'sorting', label: '排序' },
  { value: 'math', label: '数学' },
  { value: 'bit-manipulation', label: '位运算' },
  { value: 'heap', label: '堆' },
  { value: 'trie', label: '字典树' },
  { value: 'stack', label: '栈' },
  { value: 'queue', label: '队列' },
  { value: 'hash-table', label: '哈希表' },
  { value: 'depth-first-search', label: '深度优先搜索' },
  { value: 'breadth-first-search', label: '广度优先搜索' },
  { value: 'union-find', label: '并查集' },
  { value: 'prefix-sum', label: '前缀和' },
  { value: 'sliding-window', label: '滑动窗口' },
  { value: 'two-pointers', label: '双指针' },
  { value: 'monotonic-stack', label: '单调栈' },
  { value: 'recursion', label: '递归' },
  { value: 'divide-and-conquer', label: '分治' }
]

// 下拉选项（含“全部”）
const difficultyOptions = [
  { value: '', label: '全部难度' },
  { value: 'Easy', label: '简单' },
  { value: 'Medium', label: '中等' },
  { value: 'Hard', label: '困难' }
]
const tagOptions = [{ value: '', label: '全部标签' }, ...availableTags]
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 'solved', label: '已解决' },
  { value: 'attempted', label: '尝试过' },
  { value: 'not-started', label: '未开始' }
]

// 按钮显示文本
const difficultyLabel = computed(() => {
  const found = difficultyOptions.find(o => o.value === selectedDifficulty.value)
  return found ? found.label : '全部难度'
})
const tagLabel = computed(() => {
  const found = tagOptions.find(o => o.value === selectedTag.value)
  return found ? found.label : '全部标签'
})
const statusLabel = computed(() => {
  const found = statusOptions.find(o => o.value === selectedStatus.value)
  return found ? found.label : '全部状态'
})

// 计算属性
const selectedFilters = computed(() => {
  const filters: string[] = []
  if (selectedDifficulty.value) filters.push('difficulty')
  if (selectedTag.value) filters.push('tag')
  if (selectedStatus.value) filters.push('status')
  if (showFavorite.value) filters.push('favorite')
  return filters
})

// 方法
const handleSearch = () => {
  updateModelValue()
  emit('search')
}

const handleFilter = () => {
  updateModelValue()
  emit('filter')
}

const clearFilters = () => {
  searchQuery.value = ''
  selectedDifficulty.value = ''
  selectedTag.value = ''
  selectedStatus.value = ''
  showFavorite.value = false
  updateModelValue()
  emit('filter')
}

const toggleFavorite = () => {
  showFavorite.value = !showFavorite.value
  updateModelValue()
  emit('filter')
}

const updateModelValue = () => {
  const newValue = {
    search: searchQuery.value,
    difficulty: selectedDifficulty.value,
    tag: selectedTag.value,
    status: selectedStatus.value,
    favorite: showFavorite.value
  }
  emit('update:modelValue', newValue)
}
</script>

<style scoped>
/* 自定义下拉项的悬浮蓝色高亮 */
/* Headless UI 列表项通过 active 状态控制，这里仅做补充基础样式 */
</style>
